package rss;
use strict;
use warnings;
use XML::DOM;
use display_items;
use lib::SimpleLogger;
use lib::RokuUI;

our @ISA = qw(display_items);

our $last_fetch = 0;
our @headlines;

our $logger = SimpleLogger->new($DEBUG);

# ---------------------------------------------------------------------
# Constructor
sub new {
    my ($class, %params) = @_;
	my $self = {};
	$self->{'rss'} = $params{'rss'};
	bless $self, $class;
};
# ---------------------------------------------------------------------


# ---------------------------------------------------------------------

sub get_items {
	my $self=shift;
	my $rss = $self->{'rss'};

	if ((time()-$last_fetch) > (20 * 60)) {  # fetch every 20 min
		$logger->info("getting headlines from $rss");

		$last_fetch = time();

		$self->{'display'}->clear();
		$self->{'display'}->msg(text=>"Collecting", duration=>0, x=>0, y=>0, keygrab=>1);
		$self->{'display'}->msg(text=>"news stories".sprintf("%c",0x88), duration=>0, x=>0, y=>1, keygrab=>1);

		@headlines = $self->getnews($rss);

		$self->{'display'}->clear();
	}
	return @headlines;
}


# ---------------------------------------------------------------------
# fetch RSS
#
# doesn't work with heise ...
sub getnews {
	my ($self, $rss) = @_;
	my @news_title;
	my @news_description;

	my $parser = new XML::DOM::Parser;
	my $feed = $parser->parsefile($rss);
	my $root = $feed->getDocumentElement();

	foreach my $item ($root->getElementsByTagName('item')) {
		foreach my $child ($item->getElementsByTagName('title')) {
			if ($child->getNodeType == TEXT_NODE){
				push (@news_title, $child->getData());
			} elsif ($child->getNodeType == ELEMENT_NODE) {
				push (@news_title, $child->getFirstChild()->getData());
			}
		}
		foreach my $child ($item->getElementsByTagName('description')) {
			if ($child->getNodeType == TEXT_NODE){
				push (@news_description, $child->getData());
			} elsif ($child->getNodeType == ELEMENT_NODE) {
				push (@news_description, $child->getFirstChild()->getData());
			}
		}
	}
	return (@news_title);
}

# ---------------------------------------------------------------------

1;